package me.acomma.groot.application.menu;

import me.acomma.groot.domain.menu.Menu;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MenuUtil {
    public static List<Menu> buildTree(List<Menu> menus) {
        if (CollectionUtils.isEmpty(menus)) {
            return new ArrayList<>();
        }
        Map<Long, Menu> forest = new HashMap<>();
        List<Menu> tree = new ArrayList<>();
        for (Menu menu : menus) {
            forest.put(menu.getMenuId().getId(), menu);
            if (menu.getParentId() == null) {
                tree.add(menu);
                continue;
            }
            forest.get(menu.getParentId().getId()).getChildren().add(menu);
        }
        return tree;
    }
}
